<?php
include("header.php");
require_once("twitteroauth/twitteroauth.php");
require_once("configuration.php");
require_once("parser/parser.php");

//var_dump($_SESSION["username"]);

//connect to the database to retrieve the tokens for twitter connections
$database = mysql_connect("localhost", "root", "root");
if(!$database){
	echo 'We are sorry: there are some problems while connecting to the database. Please, try later.CONNECT';
} else {
	$select = mysql_select_db('streamtube', $database);
	if(!$select){
		echo 'We are sorry: there are some problems while connecting to the database. Please, try later. SELECT';
	}

	//create twitteroauth to connect to the database
	$twitteroauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['user_oauth_token'], $_SESSION['user_oauth_token_secret']);

	//gets tweets
	$tweets=$twitteroauth->get('statuses/home_timeline');

	foreach($tweets as $tweet){

		//parse the tweet
		$id_tweet=$tweet->{'id_str'};
		$tweet_author=$tweet->{'user'}->{'name'};
		$tweet_time=$tweet->{'created_at'};
		$tweetsParse = new Parser($tweet->{'text'});
		$tweetsParse->split_message();

		//if has a youtube url add to the database
		$replyParser = $tweetsParse->search_for_video();
		if(!empty($replyParser)){
			foreach($replyParser as $video){
				if(strpos($video, "watch") !== false){
					var_dump(strpos($video, "watch"));
					//check if tweet already in database
					$checkQuery = "SELECT * FROM tweets WHERE username = '".$_SESSION['username']."' and id_tweet='".$id_tweet."'";
					$check = mysql_num_rows(mysql_query($checkQuery));
					if($check){
						//echo "Entry already in the database";
						//var_dump($check);
					}else {
						$pos = strpos($video, "?v=");
						$id = substr($video, $pos+3, 11);
						$doc = new DOMDocument();
						$doc->load('http://gdata.youtube.com/feeds/api/videos/'.$id);
						$title = $doc->getElementsByTagName('title')->item(0);
						$query = "INSERT INTO `streamtube`.`tweets` (`id`, `id_tweet`, `username`, `author`, `tweet_content`, `youtube_url`, `deleted`, `new`, `favorite`, `time`, `title`) VALUES (NULL, '".$id_tweet."', '".$_SESSION['username']."', '".$tweet_author."', '".mysql_real_escape_string($tweet->{'text'})."', '".$video."', '0', '1', '0', '".$tweet_time."', '".$title->textContent."');";
						$reply = mysql_query($query);

						if(!$reply){
							echo 'We are sorry: there are some problems while connecting to the database. Please, try later.REPLY';
						}
					}
				}else{
					var_dump(strpos($video, "watch"));
				}
			}
		}
	}
}
mysql_close();
?>